package com.yanqu.road.web.controller.usercenter.newadmin;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossServerInfoDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;
import com.yanqu.road.entity.servercenter.group.CricketServerGroup;
import com.yanqu.road.entity.web.ICrossWebService;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.CrossServerType;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 61.促织竞技场分组
 */
@RestController
@RequestMapping("/usercenter/admin")
public class CenterCrossCricketServerGroupController {


    /**
     *  61.1 新增
     */
    @ResponseBody
    @RequestMapping(value = "addCricketGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addCricketGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        String serverIds = jsonObject.getString("serverIds");
        int isOpen = jsonObject.getIntValue("isOpen");

        int maxGroupId = new AdminCommonDaoImpl().getCrossCricketGroupMaxId();

        boolean b = new AdminCommonDaoImpl().addCricketGroup(++maxGroupId, channelId, serverIds, isOpen);

        if(b){
            return AdminResult.defaultInstance().toJsonString();
        }

        return AdminResult.failMsg("新增失败").toJsonString();
    }

    /**
     *  61.2 修改
     */
    @ResponseBody
    @RequestMapping(value = "updateCricketGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String updateCricketGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        int id = jsonObject.getIntValue("id");
        String serverIds = jsonObject.getString("serverIds");
        int isOpen = jsonObject.getIntValue("isOpen");

        boolean b = new AdminCommonDaoImpl().updateCricketGroup(id, channelId, serverIds, isOpen);

        if(b){
            return AdminResult.defaultInstance().toJsonString();
        }

        return AdminResult.failMsg("新增失败").toJsonString();
    }

    /**
     *  61.3 刷新
     */
    @ResponseBody
    @RequestMapping(value = "reloadCricketServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String reloadCricketServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");

        List<ProcessInfo> processInfoList = new ArrayList<>();

        List<CrossServerInfo> serverInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);
        serverInfoList.removeIf(next -> (next.getCrossServerType() != CrossServerType.RANK_CROSS_1) && (next.getCrossServerType() != CrossServerType.RANK_CROSS_2) );

        for (CrossServerInfo crossServerInfo : serverInfoList) {
            if(Config.isDebug() && crossServerInfo.getCrossServerId() != 99900077 && crossServerInfo.getCrossServerId() != 99900177 && crossServerInfo.getCrossServerId() != 99905020 && crossServerInfo.getCrossServerId() != 99905001){
                continue;
            }

            for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                if(processInfo.getServerName().equals("cross_server")) {
                    processInfoList.add(processInfo);
                }
            }
        }

        ExecutorService webExecutor = WebServer.getWebExecutor();
        List<Long> errorCrossServerIdList = new ArrayList<>();
        try {
            //遍历异步通知活动跨服
            CountDownLatch countDownLatch = new CountDownLatch(processInfoList.size());
            JSONObject param = new JSONObject();
            param.put("content", "CricketServerGroupMgr");
            for (ProcessInfo processInfo : processInfoList) {
                webExecutor.execute(() -> {
                    try {
                        String url = "http://" + processInfo.getAddress() + ":" + processInfo.getAdminPort() + "/crossws?wsdl";
                        QName qName = new QName("http://webservice.server.road.yanqu.com/", "GrossWebServiceService");
                        Service service = Service.create(new URL(url), qName);
                        ICrossWebService crossWebService = service.getPort(ICrossWebService.class);
                        String resp = crossWebService.executeAdminOperate("AgentReload|reloadMgr", param.toJSONString(), "Yanqu123");
                        JSONObject result = JSONObject.parseObject(resp);
                        int status = result.getInteger("status");
                        if (status != 1) {
                            errorCrossServerIdList.add((long) processInfo.getServerId());
                        }
                    } catch (Exception e) {
                        errorCrossServerIdList.add((long) processInfo.getServerId());
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }
            //等待
            if (!countDownLatch.await(30, TimeUnit.SECONDS)) {
                ServerListMgr.getLogger().error("刷新超时");
            }
        } catch (Exception e) {
            ServerListMgr.getLogger().error("", e);
        }

        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("serverIds", StringUtils.listToString(errorCrossServerIdList, ","));
        return result.toJsonString();
    }

    /**
     *  61.4 查询
     */
    @ResponseBody
    @RequestMapping(value = "searchCricketServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String searchCricketServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        int pageNum = jsonObject.getIntValue("pageNum");
        int pageSize = jsonObject.getIntValue("pageSize");

        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);

        List<Integer> groupIdList = new AdminCommonDaoImpl().getBatchCricketGroupId(channelId);

        List<Integer> searchList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < groupIdList.size(); i++) {
            searchList.add(groupIdList.get(i));
        }

        List<CricketServerGroup> systemConfigList = new AdminCommonDaoImpl().getCricketServerGroup(searchList);

        AdminResult result = AdminResult.defaultInstance();

        result.getData().put("total", groupIdList.size());

        List<Map<String, Object>> list = new ArrayList<>();

        for (CricketServerGroup systemConfig : systemConfigList) {
            Map<String, Object> map = new HashMap<>();
            map.put("channelId", channelId);
            map.put("id", systemConfig.getGroupId());
            map.put("serverIds", StringUtils.listToString(systemConfig.getServerList(), ","));
            map.put("isOpen", systemConfig.getOpenStatus());
            list.add(map);
        }

        result.getData().put("row", list);

        return result.toJsonString();

    }

    /**
     *  61.5 删除
     */
    @ResponseBody
    @RequestMapping(value = "delCricketGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String delCricketGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        int id = jsonObject.getIntValue("id");

        boolean b = new AdminCommonDaoImpl().deleteCricketServerGroup(id);
        if(b){
            return AdminResult.defaultInstance().toJsonString();
        }

        return AdminResult.failMsg("删除失败").toJsonString();
    }

    /**
     *  61.6 批量新增
     */
    @ResponseBody
    @RequestMapping(value = "batchAddCricketServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String batchAddCricketServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");

        JSONArray importList = jsonObject.getJSONArray("importList");

        List<CricketServerGroup> list = new ArrayList<>();

        int maxGroupId = new AdminCommonDaoImpl().getCrossCricketGroupMaxId();

        for (int i = 0; i < importList.size(); i++) {
            JSONObject object = importList.getJSONObject(i);
            CricketServerGroup data = new CricketServerGroup();
            data.setChannelId(channelId);
            data.setOpenStatus(object.getIntValue("isOpen"));
            data.setServerList(StringUtils.stringToLongList(object.getString("serverIds"), ","));
            data.setGroupId(++maxGroupId);
            list.add(data);
        }

        boolean b = new AdminCommonDaoImpl().batchAddCricketServerGroup(list);

        if(b){
            return AdminResult.defaultInstance().toJsonString();
        }

        return AdminResult.failMsg("更新失败").toJsonString();
    }
}
